package com.yylending.las.lending.increase;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.Loader;
import android.view.View;
import android.widget.*;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.airbnb.lottie.LottieAnimationView;
import com.yyfax.common.CLog;
import com.yyfax.infrastructure.eventbus.EventAgent;
import com.yyfax.infrastructure.mvp.Presenter;
import com.yyfax.infrastructure.mvp.PresenterLoader;
import com.yyfax.infrastructure.statistics.StatService;
import com.yylending.las.R;
import com.yylending.las.StatIDSet;
import com.yylending.las.YJKD;
import com.yylending.las.base.BaseActivity;
import com.yylending.las.lending.process.IncreaseLimitByPolicyActivity;
import com.yylending.las.lending.process.PreIncreaseLimitActivity;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Timer;
import java.util.TimerTask;

/**
 * 获取提额状态界面(Loading界面)
 * Created by Pengrf on 2017/11/20.
 * Copyright  2017 www.yyfax.com. All Rights Reserved.
 */
public class CheckPromoteStatusActivity extends BaseActivity implements CheckPromoteStatusPresenter.View, FinishPromoteProcessPresent.View {
	private static final String TAG = CheckPromoteStatusActivity.class.getSimpleName();
	/**
	 * 检查进度
	 */
	private static final int CHECK_PROMOTE_STATUS = 3322;
	/**
	 * 结果页提交
	 */
	private static final int FINISH_PROMOTE_PROCESS = 3321;
	/**
	 * 页面转圈
	 */
	private static final String RESULT_LOADING = "loading";
	/**
	 * 页面错误
	 */
	private static final String RESULT_ERROR = "error";
	/**
	 * 提额成功
	 */
	private static final String RESULT_PROMOTE_COMPLETED = "promoteCompleted";
	/**
	 * 提额失败
	 */
	private static final String RESULT_PROMOTE_FAILED = "promoteFailed";
	private static final String RETRY = "300";
	private static final String CANT_RETRY = "310";
	CheckPromoteStatusModel.PromoteStatus mPromoteStatus;
	/**
	 * 图
	 */
	@BindView(R.id.increase_result_iv)
	ImageView mIncreaseResultIv;
	/**
	 * 文字1
	 */
	@BindView(R.id.increase_result_text1)
	TextView mIncreaseResultText1;
	/**
	 * 文字2
	 */
	@BindView(R.id.increase_result_text2)
	TextView mIncreaseResultText2;
	/**
	 * 按钮
	 */
	@BindView(R.id.increase_result_submit_btn)
	Button mIncreaseResultSubmitBtn;
	@BindView(R.id.check_promote_status_success_ll)
	LinearLayout mCheckPromoteStatusSuccessLl;
	/**
	 * loading父布局
	 */
	@BindView(R.id.loading_rl)
	RelativeLayout mLoadingRl;
	@BindView(R.id.increase_limit_loading_view)
	LottieAnimationView mIncreaseLimitLoadingView;
	@BindView(R.id.no_network_layout)
	RelativeLayout mNoNetworkLayout;

	CheckPromoteStatusPresenter mCheckPromoteStatusPresenter;
	FinishPromoteProcessPresent mFinishPromoteProcessPresent;

	private Timer mTimer;
	private TimerTask mTimerTask;
	private static final int TIMER_TRIGGER_TIME = 60 * 1000; // 60秒后开启循环任务
	private static final int TIMER_INTERVAL_TIME = 60 * 1000; // 1分钟请求一次

	public static void start(Activity activity) {
		Intent intent = new Intent(activity, CheckPromoteStatusActivity.class);
		activity.startActivity(intent);
	}

	@Override
	public void onLoadFinished(Loader<Presenter> loader, Presenter data, int placeholder) {
		switch (loader.getId()) {
			case CHECK_PROMOTE_STATUS:
				mCheckPromoteStatusPresenter = (CheckPromoteStatusPresenter) data;
				mCheckPromoteStatusPresenter.attach(this);
				mCheckPromoteStatusPresenter.getPromoteStatus();
				break;
			case FINISH_PROMOTE_PROCESS:
				mFinishPromoteProcessPresent = (FinishPromoteProcessPresent) data;
				mFinishPromoteProcessPresent.attach(this);
				break;
		}
	}

	@Override
	public Loader<Presenter> onCreateLoader(int id, Bundle args) {
		switch (id) {
			case CHECK_PROMOTE_STATUS:
				return new PresenterLoader<>(this, new CheckPromoteStatusPresenter.Generator());
			case FINISH_PROMOTE_PROCESS:
				return new PresenterLoader<>(this, new FinishPromoteProcessPresent.Generator());
			default:
				return null;
		}
	}

	@Override
	public void checkPromoteStatusSuccess(CheckPromoteStatusModel.PromoteStatus promoteStatus) {
		mPromoteStatus = promoteStatus;
		CLog.i(TAG, "promoteStatus.code================>" + promoteStatus.code);
		switch (promoteStatus.code) {
			case RESULT_LOADING:
				StatService.onEvent(CheckPromoteStatusActivity.this, StatIDSet.EVENT_ID_POLICY_IN_VERIFICATION);
				break;
			case RESULT_ERROR:
				StatService.onEvent(CheckPromoteStatusActivity.this, StatIDSet.EVENT_ID_POLICY_NEED_REVALIDATE);
				showResultView();
				stopTimer();
				mIncreaseResultIv.setImageResource(R.drawable.ic_error_account);
				mIncreaseResultText1.setVisibility(View.VISIBLE);
				mIncreaseResultText2.setVisibility(View.VISIBLE);
				mIncreaseResultSubmitBtn.setText(R.string.recheck);
				break;
			case RESULT_PROMOTE_COMPLETED:
				StatService.onEvent(CheckPromoteStatusActivity.this, StatIDSet.EVENT_ID_POLICY_PASSED);
				showResultView();
				stopTimer();
				mIncreaseResultIv.setImageResource(R.drawable.ic_increase_limit_success);
				mIncreaseResultText2.setVisibility(View.GONE);
				mIncreaseResultText1.setText(R.string.check_success);
				mIncreaseResultSubmitBtn.setText(R.string.check_limit);
				break;
			case RESULT_PROMOTE_FAILED:
				StatService.onEvent(CheckPromoteStatusActivity.this, StatIDSet.EVENT_ID_POLICY_NOT_PASSED);
				showResultView();
				stopTimer();
				mIncreaseResultIv.setImageResource(R.drawable.ic_increase_limit_failure);
				mIncreaseResultText1.setText(R.string.sorry_increase_failure);
				mIncreaseResultText2.setVisibility(View.VISIBLE);
				mIncreaseResultText2.setText(R.string.sorry_increase_failure2);
				mIncreaseResultSubmitBtn.setText(R.string.complete);
				break;
			default:
				break;
		}
	}

	private void showResultView() {
		mIncreaseLimitLoadingView.cancelAnimation();
		mIncreaseLimitLoadingView.clearAnimation();
		mNoNetworkLayout.setVisibility(View.GONE);
		mLoadingRl.setVisibility(View.GONE);
		mCheckPromoteStatusSuccessLl.setVisibility(View.VISIBLE);
	}

	private void showLoadingView() {
		mNoNetworkLayout.setVisibility(View.GONE);
		mCheckPromoteStatusSuccessLl.setVisibility(View.GONE);
		mIncreaseLimitLoadingView.playAnimation();
		mLoadingRl.setVisibility(View.VISIBLE);
	}

	private void showNoNetworkView() {
		mIncreaseLimitLoadingView.cancelAnimation();
		mIncreaseLimitLoadingView.clearAnimation();
		mLoadingRl.setVisibility(View.GONE);
		mCheckPromoteStatusSuccessLl.setVisibility(View.GONE);
		mNoNetworkLayout.setVisibility(View.VISIBLE);
	}

	@Override
	public void checkPromoteStatusFail(String msg) {
		stopTimer();
		showNoNetworkView();
	}

	@Override
	public void finishPromoteProcessSuccess(FinishPromoteProcessModel.PromoteResult promoteResult) {
		switch (promoteResult.promoteAmount) {
			case RETRY:        //300重试(返回登录一账通界面)
				IncreaseLimitByPolicyActivity.start(this, false);
				finish();
				break;
			case CANT_RETRY:    //310 不可提额
				finish();
				break;
			default:
				break;
		}
	}

	@Override
	public void finishPromoteProcessFail(String msg) {
		showToast(msg);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_check_promote_status);
		ButterKnife.bind(this);
		setBtnBackVisible(false);
		setTitle(R.string.check_policy);
		initView();
		getSupportLoaderManager().initLoader(CHECK_PROMOTE_STATUS, null, this);
		getSupportLoaderManager().initLoader(FINISH_PROMOTE_PROCESS, null, this);
		EventAgent.register(this);
	}

	@Override
	protected void onDestroy() {
		EventAgent.unregister(this);
		stopTimer();
		getSupportLoaderManager().destroyLoader(CHECK_PROMOTE_STATUS);
		getSupportLoaderManager().destroyLoader(FINISH_PROMOTE_PROCESS);
		super.onDestroy();
	}

	private void initView() {
		showLoadingView();
	}

	@Subscribe(threadMode = ThreadMode.MAIN)
	public void onTimerEvent(TimerEvent timerEvent) {
		if (mCheckPromoteStatusPresenter != null && YJKD.login()) {
			mCheckPromoteStatusPresenter.getPromoteStatus();
		}
	}

	@Override
	protected void onStart() {
		super.onStart();
		startTimer();
	}

	@Override
	protected void onStop() {
		stopTimer();
		super.onStop();
	}

	private void startTimer() {
		stopTimer();
		mTimer = new Timer();
		mTimerTask = new TimerTask() {
			@Override
			public void run() {
				EventAgent.post(new TimerEvent());
			}
		};
		mTimer.schedule(mTimerTask, TIMER_TRIGGER_TIME, TIMER_INTERVAL_TIME);
	}

	private void stopTimer() {
		if (mTimer != null) {
			mTimer.cancel();
			mTimer.purge();
			mTimer = null;
		}
	}

	/**
	 * 调用定时事件
	 */
	class TimerEvent {
	}

	@OnClick({R.id.increase_result_submit_btn, R.id.no_network_layout})
	public void onViewClicked(View view) {
		switch (view.getId()) {
			case R.id.increase_result_submit_btn:
				finishPromote();
				break;
			case R.id.no_network_layout:
				showLoadingView();
				mCheckPromoteStatusPresenter.getPromoteStatus();
				startTimer();
				break;
		}
	}

	private void finishPromote() {
		FinishPromoteProcessModel.FinishPromoteParams finishParams = new FinishPromoteProcessModel.FinishPromoteParams("");
		// 发起网络请求
		switch (mPromoteStatus.code) {
			case RESULT_ERROR:
				finishParams.type = "err";
				mFinishPromoteProcessPresent.finishPromoteProcess(finishParams);
				break;
			case RESULT_PROMOTE_COMPLETED:
			case RESULT_PROMOTE_FAILED:
				finishParams.type = "fin";
				mFinishPromoteProcessPresent.finishPromoteProcess(finishParams);
				break;
			default:
				break;
		}
	}

	@Override
	public void onBackPressed() {
		moveTaskToBack(true);
	}

	@Override
	public void onFunctionalError(Throwable e, boolean autoTips, int functionalCode) {
		switch (functionalCode) {
			case CheckPromoteStatusModel.CHECK_PROMOTE_STATUS:
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						dismissLoading();
						stopTimer();
						showNoNetworkView();
					}
				});
				break;
			case FinishPromoteProcessModel.FINISH_PROMOTE_PROCESS:
				super.onFunctionalError(e, autoTips, functionalCode);
				break;
			default:
				break;
		}
	}
}
